/**
 * Copyright 2009 Sergio Bossa
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */
package com.googlecode.actorom.impl.core.reactor.os;

import com.googlecode.actorom.impl.core.reactor.MessageDemultiplexer;
import com.googlecode.actorom.impl.core.reactor.MessageDispatcher;
import com.googlecode.actorom.impl.core.reactor.MessageHandle;
import com.googlecode.actorom.impl.core.reactor.MessageHandler;
import com.googlecode.actorom.impl.core.reactor.MessageQueue;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import net.jcip.annotations.ThreadSafe;

/**
 * @author Sergio Bossa
 */
@ThreadSafe
public class OSMessageDispatcher implements MessageDispatcher {

    private final Map<Object, MessageHandler> handlers = new HashMap<Object, MessageHandler>();
    private final Set busyHandlers = new HashSet();
    private final ExecutorService handlerExecutor;
    private volatile Thread selectorThread = null;
    private volatile boolean active = false;

    public OSMessageDispatcher(int threadPoolSize) {
        this.handlerExecutor = Executors.newFixedThreadPool(threadPoolSize);
    }

    public synchronized void registerHandler(Object key, MessageHandler handler) {
        handlers.put(key, handler);
    }

    public synchronized void unregisterHandler(Object key) {
        handlers.remove(key);
    }

    public void dispatch(final MessageDemultiplexer messageDemultiplexer, final MessageQueue messageQueue) {
        if (!active) {
            active = true;
            selectorThread = new Thread() {

                @Override
                public void run() {
                    while (active) {
                        try {
                            messageDemultiplexer.select(messageQueue);
                            try {
                                List<MessageHandle> selectedHandles = messageDemultiplexer.acquireSelectedMessages();
                                Map<MessageHandle, MessageHandler> reservedHandles = reserve(selectedHandles);
                                for (Map.Entry<MessageHandle, MessageHandler> entry : reservedHandles.entrySet()) {
                                    final MessageHandle handle = entry.getKey();
                                    final MessageHandler handler = entry.getValue();
                                    handlerExecutor.execute(new Runnable() {

                                        public void run() {
                                            handler.handle(handle);
                                            free(handle);
                                            messageDemultiplexer.wakeUp(messageQueue);
                                        }
                                    });
                                }
                            } finally {
                                messageDemultiplexer.releaseSelectedMessages();
                            }
                        } catch (InterruptedException ex) {
                        }
                    }
                }
            };
            selectorThread.start();
        }
    }

    public void shutdown() {
        if (active) {
            active = false;
            selectorThread.interrupt();
            handlerExecutor.shutdownNow();
        }
    }

    private synchronized Map<MessageHandle, MessageHandler> reserve(List<MessageHandle> handles) {
        Map<MessageHandle, MessageHandler> result = new HashMap<MessageHandle, MessageHandler>();
        Iterator<MessageHandle> iterator = handles.iterator();
        while (iterator.hasNext()) {
            MessageHandle handle = iterator.next();
            Object key = handle.getKey();
            if (!busyHandlers.contains(key)) {
                MessageHandler handler = handlers.get(key);
                result.put(handle, handler);
                busyHandlers.add(key);
                iterator.remove();
            }
        }
        return result;
    }

    private synchronized void free(MessageHandle handle) {
        busyHandlers.remove(handle.getKey());
    }
}
